import {getToken, removeToken} from "@/utils/auth";

interface RequestOptions {
  url: string;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  data?: any;
  header?: Record<string, string>;
}

interface Error {
	message: string;
}

interface ErrorConstructor {
    new(message?: string): Error;
    (message?: string): Error;
    readonly prototype: Error;
}

// api/request.ts
interface RequestOptions {
  url: string;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  data?: any;
  header?: Record<string, string>;
}

export function request(options: RequestOptions): Promise<any> {
	const url = import.meta.env.VITE_BASE_URL + options.url
	const header = options.header || {}
	header['Authorization'] = getToken()

  return new Promise((resolve, reject) => {
    uni.request({
      url: url,
      method: options.method || 'GET',
      data: options.data || {},
      header: header,
      success: res => {
        if (res.data.code === 0) {
          return resolve(res.data);
        }

        // 登陆失效
        if (res.statusCode === 401) {
          // 清除本地token
          removeToken()
          // 弹框未登录
          // todo.可改为跳转到登录页面
          uni.showToast({
            icon: 'none',
            duration: 3000,
            title: '请先登录小程序'
          });
          return reject(new Error('请先登录小程序' || 'Error'));
        }

        // 其他异常错误码
        uni.showToast({
          icon: 'none',
          duration: 3000,
          title: `${res.data.more_info}`
        });
        return reject(new Error(res.data.more_info || 'Error'));
      },
      fail: err => {
        // 请求失败弹窗
        uni.showToast({
          icon: 'none',
          duration: 3000,
          title: '服务器错误,请稍后再试'
        });
        return reject(err);
      }
    });
  });
}

